package State;

import beans.SenSorReading;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;
import scala.Tuple3;

public class State_KeyedStateApplicationCase {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<String> inputStream = env.readTextFile("src/main/resources/sensor.txt");

        SingleOutputStreamOperator<SenSorReading> dataStream = inputStream.map(line -> {
            String[] fields = line.split(",");
            return new SenSorReading(fields[0], new Long(fields[1]), new Double(fields[2]));
        });

        SingleOutputStreamOperator<Tuple3<String, Double, Double>> result = dataStream
                .keyBy("id")
                .flatMap(new TempChangeWarning(10.0));

        result.print();
        env.execute();
    }

    public static class TempChangeWarning extends RichFlatMapFunction<SenSorReading, Tuple3<String, Double, Double>> {

        //温度阈值
        private Double threshold;

        public TempChangeWarning(Double threshold) {
            this.threshold = threshold;
        }

        //定义状态，保存上一次的温度值
        private ValueState<Double> lastTempState;

        @Override
        public void open(Configuration parameters) throws Exception {
            lastTempState = getRuntimeContext().getState(new ValueStateDescriptor<Double>("lastTempState", Double.class));
        }

        @Override
        public void flatMap(SenSorReading senSorReading, Collector<Tuple3<String, Double, Double>> collector) throws Exception {
            Double lastTemp = lastTempState.value();
            if (lastTemp != null) {
                Double diff = Math.abs(lastTemp - senSorReading.getTimeStamp());
                if (diff >= threshold) {
                    collector.collect(new Tuple3<>("温差过大警告", lastTemp, senSorReading.getTemperature()));
                }
            }
            //更新状态
            lastTempState.update(senSorReading.getTemperature());
        }

        //清空
        @Override
        public void close() throws Exception {
            lastTempState.clear();
        }
    }
}
